package com.eric.utils;

import cn.hutool.core.collection.CollUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description： 手动分页工具类
 * @Author: liuBing
 * @DateTime: 2022/5/5 14:45
 */
public class PageUtil {


    public static <T> Map<String, T> mapPage(Map<String, T> map, Integer pageNum, Integer pageSize) {
        List<Map.Entry<String, T>> entryList = new ArrayList<>(map.entrySet());

        return startPage(entryList, pageNum, pageSize)
                .stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }


    /**
     * list 分页
     */
    public static <T> List<T> startPage(List<T> list, Integer pageNum, Integer pageSize) {
        if (CollUtil.isEmpty(list)) {
            return list;
        }

        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        // 记录总数
        Integer count = list.size();
        // 页数
        int pageCount = 0;

        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        // 开始索引
        int fromIndex = 0;
        // 结束索引
        int toIndex = 0;

        if (pageNum > pageCount) {
            list.clear();
            return list;
        } else if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        return list.subList(fromIndex, toIndex);
    }
}
